'use strict'
const router=require('koa-router')();
const fs=require('fs')

//获取路由文件
function getRouterfile(data){
    let tmpPath=data || __dirname;
    let resfile=fs.readdirSync(tmpPath);
    let result=resfile.filter(item=>{
      return  item.endsWith('.js') && item !== 'index.js'
    })
    return result;
}

//注册路由
function registerRouter(router,result){
    result.forEach(res=>{
        let tmpPath=res +'/' +__dirname;
        let obj=require(tmpPath)
        for(let key in obj){
            let tmpArr=key.split(' ');
            let rou_Url=tmpArr[1];
            let rou_method=tmpArr[0];
            let rou_fn=obj[key];
            if (rou_method==='get') {
                router.get(rou_Url,rou_fn)
            }else if(rou_method==='put'){
                router.put(rou_Url,rou_fn)
            }else if(rou_method==='post'){
                router.post(rou_Url,rou_fn)
            }else if(rou_method==='delete'){
                router.delete(rou_Url,rou_fn)
            }else{

            }
            
        }
        return router.routes();
    })
}

module.exports=function(){
    let f1=getRouterfile();
    let f2=registerRouter(router,f1);
    return f2;
}